package cn.cqone.crm.controller;

import cn.cqone.crm.domain.Customer;
import cn.cqone.crm.domain.CustomerTransfer;
import cn.cqone.crm.domain.Employee;
import cn.cqone.crm.query.CustomerTransferQuery;
import cn.cqone.crm.service.CustomerService;
import cn.cqone.crm.service.CustomerTransferService;
import cn.cqone.crm.service.EmployeeService;
import cn.cqone.crm.utils.JSONResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@ResponseBody
@RequestMapping("/cusTransfer")
@CrossOrigin
@RequiresPermissions("cutomer_transfer:main")
public class CustomerTransferController extends BaseController<CustomerTransfer,Long,CustomerTransferQuery> {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private CustomerTransferService customerTransferService;

    //移交
    @RequestMapping(value = "/transfer/{id}/{newSeller_id}/{traceUser_id}",method = RequestMethod.POST)
    public JSONResult moveCus(@RequestBody CustomerTransfer customerTransfer,
                              @PathVariable("id") Long id,
                              @PathVariable("newSeller_id") Long newSeller_id,
                              @PathVariable("traceUser_id") Long traceUser_id){
        try{
            Customer customer = customerService.findById(id);
            Employee newSeller = employeeService.findById(newSeller_id);
            Employee traceUser = employeeService.findById(traceUser_id);
            customer.setSeller_id(newSeller);
            customerService.transferSeller(customer);
            customerTransfer.setCustomer_id(customer);
            customerTransfer.setNewSeller_id(newSeller);
            customerTransfer.setTransUser_id(traceUser);
            System.out.println(customerTransfer);
            customerTransferService.add(customerTransfer);
            return JSONResult.ok();
        }catch (Exception e){
            e.printStackTrace();
            return JSONResult.error("修改失败！");
        }
    }

    //选择新的市场专用的下拉框展示
    @RequestMapping(value = "/newSellerAll/{seller_id}",method = RequestMethod.POST)
    public JSONResult newSellerAll(@PathVariable("seller_id") Long seller_id) {
        try {
            List<Employee> list = employeeService.findAll();
            Employee oldSeller = employeeService.findById(seller_id);
            for (int i = 0; i < list.size(); i++) {
                if(list.get(i).getId() == oldSeller.getId()){
                    list.remove(i);
                }
            }
            list.forEach(employee -> System.out.println(employee));
            return JSONResult.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            return JSONResult.error("服务器异常 公司可能倒闭了！");
        }
    }
}
